package com.useeinfo.oa.modules.base.dao;

import com.useeinfo.framework.extend.dao.CrudDao;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.data.QueryUtils;
import com.useeinfo.framework.sugar.data.SelectVO;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.modules.base.entity.Position;
import net.sf.json.JSONArray;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import java.util.*;

/**
 * @Date: 2018/12/3 17:05
 * @Description:
 */
@Repository("positionDao")
public class PositionDao implements CrudDao<Position> {

    private final static Logger logger = LoggerFactory.getLogger(PositionDao.class);

    @PersistenceContext
    private EntityManager entityManager;

    //根据部门id查询岗位List
    public List<SelectVO> getPositionByOrgna(String organizationId,String enterpriseId) {
        String sql = "SELECT * FROM position p WHERE  p.delete_status= false and p.id in (select pp.position_id FROM system_user_2_position pp WHERE pp.system_user_id in" +
                "(select er.id FROM system_user er WHERE  er.delete_status= false and er.id in (select sor.system_user_id FROM system_user_organization sor WHERE  sor.delete_status= false  and sor.organization_id="+organizationId+")" +
                "and er.id in(select en.system_user_id FROM enterprise_personnel_system_user en where en.delete_status= false and en.enterprise_id= "+enterpriseId+" ))) and p.enterprise_id ="+enterpriseId;
        logger.info("拼接完成的sql语句为：{}",sql);
        List<Object>objects=entityManager.createNativeQuery(sql).getResultList();
        List<SelectVO> selectVOS=new ArrayList<>();
        if (CollectionUtils.isNotEmpty(objects)) {
            for (Object object : objects) {
                JSONArray jsonArray1 = JSONArray.fromObject(object);
                SelectVO selectVO=new SelectVO();
                selectVO.setValue(jsonArray1.get(0).toString());
                selectVO.setText(jsonArray1.get(5).toString());
                selectVOS.add(selectVO);
            }
        }
        return selectVOS;
    }

    //根据区域id查询岗位List
    public List<Object> getPositionByArea(String areaId,String enterpriseId,int no,int size,int type,String authorityName) {
        String search;
        if(type==0){
            search="p.id";
        }else{
            search="count(*)";
        }
        String sql = "SELECT "+search+" FROM position p WHERE  p.delete_status= false and p.id in (select pp.position_id FROM system_user_2_position pp WHERE pp.system_user_id in" +
                " (select er.id FROM system_user er WHERE er.delete_status= false and er.id in (select ep.system_user_id FROM enterprise_personnel_system_user ep WHERE  ep.delete_status= false and ep.enterprise_id="+enterpriseId+") " ;
        if(areaId!=null){
            sql=sql+ " AND er.id in (select pa.system_user_id FROM system_user_2_area pa WHERE pa.area_id="+areaId+") " ;
        }
        sql=sql+ " AND er.id in (select ue.user_id FROM user_role_enterprise ue WHERE  ue.delete_status= false and ue.role_id in (select su.role_id FROM system_role_2_authority su WHERE su.authority_id in " +
                " (Select sya.id FROM system_authority sya WHERE sya.authority_name='"+authorityName+"')))))";
        if(type==0){
            sql=sql+"limit "+(no-1)*size+"," +size;
        }
        logger.info("拼接完成的sql语句为：{}",sql);
        List<Object>objects=entityManager.createNativeQuery(sql).getResultList();
        if(CollectionUtils.isNotEmpty(objects)){
            return objects;
        }else{
            return null;
        }
    }



    @Override
    public Map<String, Object> getSearchCondition(Map<String, String> queryHash) {
        Map<String, Object> conditionHash = new HashMap<>();
        conditionHash.put("s.deleteStatus = ?{paramIndex} ", false);
        if (queryHash == null || queryHash.size() == 0) {
            return conditionHash;
        }
        for (String key : queryHash.keySet()) {
            String value = queryHash.get(key);
            switch (key) {
                case "enterpriseId":
                    conditionHash.put("s.enterprise.id = ?{paramIndex}", StringConverters.null2Long(value));
                    continue;
                case "positionName":
                    conditionHash.put("s.name like ?{paramIndex}", "%" + value + "%");
                    continue;
                case "positionCode":
                    conditionHash.put("s.code like ?{paramIndex}", "%" + value + "%");
                    continue;
            }
        }

        return conditionHash;
    }

    @Override
    public Long totalRecord(Map<String, String> queryHash) {

        Map<String, Object> conditions = getSearchCondition(queryHash);
        TypedQuery<Long> typedQuery = QueryUtils.getTypedQueryByCondition("select count(s) from Position s ", conditions, entityManager, Long.class);
        return typedQuery.getSingleResult();
    }

    @Override
    public List<Position> findList(QueryParam queryParam) {
        String sqlInfo = queryParam.joinJPQL("select s from Position s ", "order by s.id desc ");
        Map<String, Object> conditions = getSearchCondition(queryParam.getSqlMap());
        TypedQuery<Position> typedQuery = QueryUtils.getTypedQueryByCondition(sqlInfo, conditions, entityManager, Position.class);
        return queryParam.findPageList(typedQuery);
    }

    @Override
    public Position findModel(Long userId) {
        return entityManager.find(Position.class, userId);
    }

    @Override
    public Integer add(Position position) {
        position.setCreateDate(new Date());
        entityManager.persist(position);
        logger.info("PositionDaoImpl添加position成功！");
        return 1;
    }

    @Override
    public Integer update(Position position) {
        position.setUpdateDate(new Date());
        entityManager.merge(position);
        return 1;
    }

    @Override
    public Integer delete(Long positionId) {
        Position position = entityManager.find(Position.class, positionId);
        entityManager.remove(position);
        return 1;
    }

    @Override
    public Integer deleteLogic(Position model) {
        model.setDeleteStatus(true);
        return 1;
    }


    public List<Position> hqlExcute(String hql) {
        return entityManager.createQuery(hql,Position.class).getResultList();
    }

    public List<Position> hqlExcute(String hql,QueryParam queryParam) {
        return queryParam.findPageList(entityManager.createQuery(hql,Position.class));
    }
}
